﻿using System;
using System.Net;
using System.Net.Sockets;

/////////////////////////////
//  Partie reseau serveur  //
/////////////////////////////

namespace Strom.Core.Network
{
    public class BaseServer
    {
        private Socket _listener;
        public bool IsRunning { get; private set; }
        public Database.BinaryDatabase Database;

        public delegate void ClientConnectedHandler(BaseClient client);
        public event ClientConnectedHandler ClientConnected;

        // Lancement du serveur (et début de l'écoute)
        public void Start(string ip, int port)
        {
            if (IsRunning) return;

            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listener.Bind(new IPEndPoint(Dns.GetHostEntry(ip).AddressList[0], port));
            _listener.Listen(0);
            IsRunning = true;
            _listener.BeginAccept(AcceptSocket, null);
        }

        // Acceptation du client (callback)
        void AcceptSocket(IAsyncResult ar)
        {
            if (!IsRunning) return;

            if (ClientConnected != null)
                ClientConnected(new BaseClient(_listener.EndAccept(ar)));

            _listener.BeginAccept(AcceptSocket, null);
        }

        // Arrêt du serveur 
        public void Stop()
        {
            if (!IsRunning) return;

            IsRunning = false;
            
            _listener.Close();
        }
    }
}